//
//  UserSupplyDemandViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/3/24.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "UserSupplyDemandViewController.h"
#import "RHTableView.h"
#import "TopToggletabView.h"

#import "MessageEvaluationTableViewCell.h"
#import "MessageCircleFriendsTableViewCell.h"
#import "TextKeyboardView.h"
#import "SupplyDemandAddViewController.h"
#import "SelectWebUrlViewController.h"

@interface UserSupplyDemandViewController ()<UISearchBarDelegate,MessageCircleFriendsTableViewCellDelegate,MessageEvaluationTableViewCellDelegate,UIAlertViewDelegate>{
    RHTableView  *table_user;
    UISearchBar *txtSearch;
    NSInteger ftempCircleFriends;
    NSIndexPath *circleFriendsIndexPath;
    TextKeyboardView *textKeyboard;
    NSString *strTempType;
    float f_tempKeyBoard;
}

@end

@implementation UserSupplyDemandViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self rightButton:nil image:@"headadd" sel:@selector(rightButtonClicked)];
    
    
    txtSearch= [[UISearchBar alloc] initWithFrame:CGRectMake(0, kTopHeight+40, kScreenWidth, 44)];
    txtSearch.delegate=self;
    txtSearch.placeholder=@"搜索";
    [self.view addSubview:txtSearch];
    [txtSearch setBackgroundImage:[[Utility Share] imageFromColor:rgbGray rect:txtSearch.frame.size]];
    
    
    [self initTabelViews];
    
    
    
    textKeyboard=[[TextKeyboardView alloc]init];
    textKeyboard.frame=CGRectMake(0, kScreenHeight, kScreenWidth, 300);
    textKeyboard.selfView_Y=kScreenHeight;
    [self.view addSubview:textKeyboard];
    
    
    [self initTopButtons];
}

-(void)initTopButtons{
    TopToggletabView *toggleTab=[[TopToggletabView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, 40)];
    [self.view addSubview:toggleTab];
    __weak UserSupplyDemandViewController *viewC=self;
    [toggleTab setTiltelArray:@[@{@"title":@"我要牌照",@"id":@"1"},@{@"title":@"我有牌照",@"id":@"2"}] toggleTab:^(NSDictionary *dicSelect) {
        [table_user.dataArray removeAllObjects];
        [table_user reloadData];
        strTempType=[dicSelect valueForJSONStrKey:@"id"];
        [viewC loadTableData];
    }];
}

-(void)initTabelViews{
    table_user=[[RHTableView alloc]initWithFrame:CGRectMake(0, kTopHeight+84, kScreenWidth, kContentHeight-84)];
    [table_user showRefresh:YES LoadMore:YES];
    table_user.delegate = self;
    table_user.dataSource = self;
    [table_user setBackgroundColor:rgbGray];
    [table_user setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:table_user];
    [table_user setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    
}

-(void)loadTableData{
    krequestParam
    [dictparam setValue:txtSearch.text forKey:@"keys"];
    [dictparam setValue:strTempType forKey:@"type"];
    [dictparam setValue:@"%@" forKey:@"page"];
    [dictparam setValue:@"20" forKey:@"pagesize"];
    table_user.urlString=[NSString stringWithFormat:@"%@%@",XKFV3mydemand,dictparam.wgetParamStr];
    [table_user refresh];
}
#pragma mark button
-(void)rightButtonClicked{
    [self pushController:[SupplyDemandAddViewController class] withInfo:strTempType withTitle:@"" withOther:nil];
}

#pragma mark tableView
#pragma mark UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  table_user.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     NSDictionary *dic=[table_user.dataArray objectAtIndex:section];
     return [[dic objectForJSONKey:@"comment"] count]+1;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.section];
        static NSString *identifier = @"identifier_left";//@"CricleFriends";
        
        MessageCircleFriendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[MessageCircleFriendsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        ftempCircleFriends= [cell setValueForDictionary:dic indexPath:indexPath type:@"noImage"];
    }else{
        [self tableView:table_user cellForRowAtIndexPath:indexPath];
    }
    return ftempCircleFriends;
   
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.section];
        static NSString *identifier = @"identifier_left";//@"CricleFriends";
        
        MessageCircleFriendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[MessageCircleFriendsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.delegate=self;
        ftempCircleFriends= [cell setValueForDictionary:dic indexPath:indexPath];
        return cell;
    }else{
        NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.section];
        static NSString *identifier = @"identifier_left_Evaluation";//
        MessageEvaluationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[MessageEvaluationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.delegate=self;
        ftempCircleFriends= [cell setValueForDictionary:[[dic objectForJSONKey:@"comment"] objectAtIndex:indexPath.row-1] indexPath:indexPath EvaluationCount:[[dic objectForJSONKey:@"comment"] count] ];////
        return cell;
        
    }

    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark MessageCircleFriendsTableViewCellDelegate
-(void)selectEvaluation:(MessageCircleFriendsTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    
    //朋友圈评论
    circleFriendsIndexPath=indexPath;
    textKeyboard.textSend.placeholder=@"说点什么...";
    __weak UserSupplyDemandViewController * viewC1=self;
    [textKeyboard setValueForDictionary:nil indexPath:circleFriendsIndexPath sendText:^(NSDictionary *dict, NSIndexPath *indexPath, NSString *txtSend) {
        [viewC1 sendEvaluationData:txtSend selectIndex:indexPath];
        
    }];
//    [self performSelector:@selector(selectTableRow) withObject:nil afterDelay:0.5];
    
    
}
-(void)selectPraise:(MessageCircleFriendsTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    //朋友圈点赞
    
    circleFriendsIndexPath=indexPath;
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setValue:[[Utility Share] userId] forKey:@"uid"];
    [dict setValue:[[Utility Share] userToken] forKey:@"token"];
    [dict setValue:[dic valueForJSONStrKey:@"id"] forKey:@"oid"];
    
    [NetEngine createPostAction:XKFV3demanddemandpraise withParams:dict onCompletion:^(id resData, BOOL isCache) {
        if ([[resData objectForJSONKey:@"status"] isEqualToString:@"200"]) {
//            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
            NSMutableDictionary *dicUpdate=[[NSMutableDictionary alloc] initWithDictionary:dic];
            [dicUpdate setValue:[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"praisenum"] forKey:@"praisenum"];
            [dicUpdate setValue:[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"status"] forKey:@"ispraise"];
            [table_user.dataArray replaceObjectAtIndex:indexPath.section withObject:dicUpdate];
//            [table_user reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            
            [sview refreshButtonPraiseStatus:dicUpdate];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];

    
}
-(void)deleteMessage:(MessageCircleFriendsTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    //朋友圈删除
      circleFriendsIndexPath=indexPath;
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setValue:[[Utility Share] userId] forKey:@"uid"];
    [dict setValue:[[Utility Share] userToken] forKey:@"token"];
    [dict setValue:[dic valueForJSONStrKey:@"id"] forKey:@"id"];
    
    
    [NetEngine createPostAction:XKFV3demanddeldemand withParams:dict onCompletion:^(id resData, BOOL isCache) {
        if ([[resData objectForJSONKey:@"status"] isEqualToString:@"200"]) {
            [table_user.dataArray removeObjectAtIndex:indexPath.section];
             [table_user reloadData];
            [SVProgressHUD showSuccessWithStatus:@"删除成功!"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
            });
            
            
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
}
-(void)selectImages:(MessageCircleFriendsTableViewCell *)sview{
    [self.view endEditing:YES];
}

#pragma mark MessageEvaluationTableViewCellDelegate
-(void)selectContent:(MessageEvaluationTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    //回复评论
    circleFriendsIndexPath=indexPath;
    if ([[dic valueForJSONStrKey:@"uid"] isEqual:[[Utility Share] userId]]) {
        
        //        commontIndex = indexPath.section;
        UIAlertView *aletv = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否要删除这条评论" delegate:self cancelButtonTitle:@"删除" otherButtonTitles:@"还是留着吧", nil];
        aletv.tag =101;
        [aletv show];
    }
    else
    {
        
        textKeyboard.textSend.placeholder=[NSString stringWithFormat:@"回复 %@ :",[dic valueForJSONStrKey:@"realnamea"]];
        __weak UserSupplyDemandViewController * viewC2=self;
        [textKeyboard setValueForDictionary:nil indexPath:circleFriendsIndexPath sendText:^(NSDictionary *dict, NSIndexPath *indexPath, NSString *txtSend) {
            [viewC2 sendEvaluationData:txtSend selectIndex:indexPath];
            
        }];
        
//        [self performSelector:@selector(selectTableRow) withObject:nil afterDelay:0.5];
    }
    
    
}

-(void)selectOneUser:(MessageEvaluationTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    [self selectContent:sview object:dic index:indexPath];
}
-(void)selectTwoUser:(MessageEvaluationTableViewCell *)sview object:(id)dic index:(NSIndexPath *)indexPath{
    [self selectContent:sview object:dic index:indexPath];
}
-(void)sendEvaluationData:(NSString *)txtSend selectIndex:(NSIndexPath *)indexPath{
    if (![txtSend notEmptyOrNull]) {
        return;
    }
    NSDictionary *dicT=[table_user.dataArray objectAtIndex:indexPath.section];
    krequestParam
    [dictparam setValue:[dicT valueForJSONStrKey:@"id"] forKey:@"lid"];
    [dictparam setValue:txtSend forKey:@"content"];
    if (indexPath.row==0) {
        [dictparam setValue:[dicT valueForJSONStrKey:@"uid"] forKey:@"backpid"];
    }else{
        NSDictionary *dt=[[dicT objectForJSONKey:@"comment"] objectAtIndex:indexPath.row-1];
        [dictparam setValue:[dt valueForJSONStrKey:@"uid"] forKey:@"backpid"];
    }
    
    [NetEngine createPostAction:XKFV3demandpushdemand withParams:dictparam onCompletion:^(id resData, BOOL isCache) {
        if ([[resData objectForJSONKey:@"status"] isEqualToString:@"200"]) {
            textKeyboard.textSend.text=@"";
            
            NSMutableDictionary *dicUpdate=[[NSMutableDictionary alloc] initWithDictionary:dicT];
            NSMutableArray *arrayUpdate=[[NSMutableArray alloc] initWithArray:[dicT objectForJSONKey:@"comment"]];
            [arrayUpdate addObject:[resData objectForJSONKey:@"data"]];
            [dicUpdate setValue:arrayUpdate forKey:@"comment"];
            [table_user.dataArray replaceObjectAtIndex:indexPath.section withObject:dicUpdate];
            [table_user reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
}
-(void)selectTableRow{
   
//    [table_user selectRowAtIndexPath:circleFriendsIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
}
-(void)selectUserIcon:(MessageCircleFriendsTableViewCell *)sview object:(NSDictionary *)dic index:(NSIndexPath *)indexPath{
    NSMutableDictionary *dicCard=[[NSMutableDictionary alloc] initWithDictionary:dic];
    [dicCard setValue:[dic valueForJSONStrKey:@"card"] forKey:@"url"];
    [dicCard setValue:[dic valueForJSONStrKey:@"uid"] forKey:@"uid"];
    [dicCard setValue:NSStringFromClass([self class]) forKey:@"controller"];
    [self pushController:[SelectWebUrlViewController class] withInfo:@"shareCard" withTitle:@" " withOther:dicCard];
}

#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==101 && buttonIndex==0) {
        //删除
        NSDictionary *dicT=[table_user.dataArray objectAtIndex:circleFriendsIndexPath.section];
        if (circleFriendsIndexPath.row==0) {
        }else{
            NSDictionary *dt=[[dicT objectForJSONKey:@"comment"] objectAtIndex:circleFriendsIndexPath.row-1];
            krequestParam
            [dictparam setValue:[dt valueForJSONStrKey:@"commentid"] forKey:@"commentid"];
            
            [NetEngine createPostAction:XKFV3demanddelcomment withParams:dictparam onCompletion:^(id resData, BOOL isCache) {
                if ([[resData objectForJSONKey:@"status"] isEqualToString:@"200"]) {
                    NSMutableDictionary *dicUpdate=[[NSMutableDictionary alloc] initWithDictionary:dicT];
                    NSMutableArray *arrayUpdate=[[NSMutableArray alloc] initWithArray:[dicT objectForJSONKey:@"comment"]];
                    [arrayUpdate removeObjectAtIndex:circleFriendsIndexPath.row-1];
                    [dicUpdate setValue:arrayUpdate forKey:@"comment"];
                    [table_user.dataArray replaceObjectAtIndex:circleFriendsIndexPath.section withObject:dicUpdate];
                    [table_user reloadSections:[NSIndexSet indexSetWithIndex:circleFriendsIndexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
                }
            }];
        }
    }
}
#pragma mark UISearchBarDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self loadTableData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self loadTableData];
    [searchBar resignFirstResponder];
}


#pragma mark selector
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    DLog(@"---->动态键盘高度:%f",distanceToMove);
    f_tempKeyBoard=distanceToMove+54;
    UITableViewCell *cell=[table_user cellForRowAtIndexPath:circleFriendsIndexPath];
    float fy=cell.frameYH-(H(table_user)-distanceToMove-54);
    fy=fy<0?0:fy;
    [table_user setContentOffset:CGPointMake(0, fy)];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    
    UITableViewCell *cell=[table_user cellForRowAtIndexPath:circleFriendsIndexPath];
    if (cell.frameYH+f_tempKeyBoard>table_user.contentSize.height) {
        float fy=table_user.contentSize.height-H(table_user);
        fy=fy<0?0:fy;
        [table_user setContentOffset:CGPointMake(0, fy)];
    }
}//


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
